//
//  CountryPickerView.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/10.
//  Copyright © 2025 考拉🐨. All rights reserved.
//
//  国家选择器
import UIKit
import Localize_Swift
import Reusable
import SnapKit

extension CountryPickerView: NibLoadable {}

class CountryPickerView: UIView {
    
    @IBOutlet weak var titleLabel: UILabel!
    
    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var resetButton: UIButton!
    @IBOutlet weak var searchButton: UIButton!
    
    @IBOutlet weak var historyLayoutHeight: NSLayoutConstraint!
    @IBOutlet weak var historyTitleLabel: UILabel!
    @IBOutlet weak var historyClearButton: UIButton!
    @IBOutlet weak var historyCollectionView: UICollectionView!
    private var historyList: [String] = []
    
    // 请选择
    @IBOutlet weak var selecteTitleLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!
    
    // MARK: 当前选择
    @IBOutlet weak var currentView: UIView!
    @IBOutlet weak var currentViewLayoutHeight: NSLayoutConstraint!
    @IBOutlet weak var currentTitleLabel: UILabel!
    
    @IBOutlet weak var currentCountryView: UIView!
    @IBOutlet weak var currentCountryLabel: UILabel!
    
    @IBOutlet weak var provinceView: UIView!
    @IBOutlet weak var currentProvinceView: UIView!
    @IBOutlet weak var currentProvinceLabel: UILabel!
    

    // 数据源 全部数据
    var dataSources: [LoginCityModel] = [] {
        didSet {
            
            currentView.isHidden = true
            currentViewLayoutHeight.constant = 0
            currentCountryView.isHidden = true
            provinceView.isHidden = true
            
            selectedCountryModel = nil
            selectedProvinceModel = nil
            selectedCityModel = nil
            
            list = Array(dataSources)
            
//            updateHistory()
            
            searchTextField.text = ""
            resetButton.isHidden = true
        }
    }
    
    // 当前展示的列表数据
    private var list: [LoginCityModel] = [] {
        didSet {
            tableView.reloadData()
        }
    }
    
    private var selectedCountryModel: LoginCityModel?
    private var selectedProvinceModel: LoginCityModel?
    private var selectedCityModel: LoginCityModel?
    
    /// 选中的城市反显，（国家，省份，城市）
    var didSelectedBlock: ((Int, String) -> Void)?
    var closeBlock: (() -> Void)?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        initUI()
        
        /// 监听语言的变化
        NotificationCenter.default.addObserver(self, selector: #selector(updateLanguageAction), name: NSNotification.Name(LCLLanguageChangeNotification), object: nil)
        updateLanguageAction()
    }
    
    // 重置搜索内容
    @IBAction func resetAction(_ sender: UIButton) {
        searchTextField.text = ""
    }
    
    @IBAction func searchAction(_ sender: Any) {
        xLog("搜索 \(searchTextField.text!)")
    }
    
    // 清空历史记录
    @IBAction func clearHistoryAction(_ sender: Any) {
        YLAlert(controller: viewController!, title: "提示".localized(), message: "确定要清空历史选择吗？", actionTitles: ["确定".localized()], cancelTitle: "取消".localized()) { action, index in
            xLog("确定")
            self.saveSearchHistory(array: [])
            self.updateHistory()
        }
    }
    
    @IBAction func closeAction(_ sender: Any) {
        closeBlock?()
    }
    
    
    @IBAction func currentCountryAction(_ sender: Any) {
        // 选中当前国家
        provinceView.isHidden = true
        list = Array(dataSources)
        tableView.reloadData()
    }
    
    @IBAction func currentProvinceAction(_ sender: Any) {
        
        guard let model = selectedProvinceModel else { return }
        
        let countryModels = dataSources.filter { $0.id == model.pid }
        if countryModels.count > 0 {
            list = countryModels.first!.children
        }
    }
    
}

// MARK: - private
private extension CountryPickerView {
    func initUI() {
        backgroundColor = .white
        frame = CGRect(x: 0, y: 0, width: xScreenW, height: xScreenH*5/6)
        addRoundedCorners(radius: 16)
        
        resetButton.addRoundedCorners(radius: 4)
        searchButton.addRoundedCorners(radius: 4)
        do {
            let layout = YLCollectionViewFlowLayout()
            layout.delegate = self
            layout.columnSpacing = 8
            layout.rowSpacing = 8
            
            historyCollectionView.setCollectionViewLayout(layout, animated: true)
            historyCollectionView.delegate = self
            historyCollectionView.dataSource = self
            
            historyCollectionView.isScrollEnabled = false
            historyCollectionView.bounces = false
            historyCollectionView.backgroundColor = .white
            historyCollectionView.showsHorizontalScrollIndicator = false
            historyCollectionView.showsVerticalScrollIndicator = false
            historyCollectionView.register(cellType: CountryPickerHistoryCell.self)
        }
       do {
            tableView.register(cellType: ReusableTableViewCell.self)
            tableView.rowHeight = 50
            tableView.delegate = self
            tableView.dataSource = self
            // .never: 第一个cell挨着屏幕顶, 否则是挨着navbar底部
            tableView.contentInsetAdjustmentBehavior = .never
            // 去掉分割线
            tableView.separatorStyle = .none
            // 修复默认分割线, 向右偏移问题
            // tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            // 分割线颜色
            // tableView.separatorColor = .red
            // iOS 15 默认情况 sectionHeaderTopPadding 会有22个像素的高度，及默认情况，TableView section header 增加22像素的高度
            if #available(iOS 15.0, *) {
                tableView.sectionHeaderTopPadding = 0
            }
        }
        currentView.isHidden = true
        currentViewLayoutHeight.constant = 0
        provinceView.isHidden = true
        
        currentCountryView.addRoundedCorners(radius: 8, width: 1, color: UIColor(hex: "F98A26"))
        currentProvinceView.addRoundedCorners(radius: 8, width: 1, color: UIColor(hex: "F98A26"))
        
        searchTextField.tintColor = .theme
        NotificationCenter.default.addObserver(self, selector: #selector(textFieldTextDidChangeNotification), name: UITextField.textDidChangeNotification, object: searchTextField)
        
    }
    
    @objc func textFieldTextDidChangeNotification(noti: Notification) {
        let textField = noti.object as! UITextField
        
        xLog(textField.text)
        
        if textField.markedTextRange != nil {
            return
        }
        
        resetButton.isHidden = textField.text!.isEmpty
        
    }
    
    // 更新语言
    @objc private func updateLanguageAction() {
        
        titleLabel.text = "城市选择".localized(.login)
        selecteTitleLabel.text = "请选择".localized(.login)
        currentTitleLabel.text = "当前选择".localized(.login)
        
        searchTextField.placeholder = "请输入城市名称"
        resetButton.setTitle("重置".localized(.login), for: .normal)
        searchButton.setTitle("搜索".localized(.login), for: .normal)
        
        historyTitleLabel.text = "历史选择".localized(.login)
        historyClearButton.setTitle("清空历史".localized(.login), for: .normal)
        
    }
    
    
    // MARK: - 历史记录
    func updateHistory() {
        historyList = fetchSearchHistoryList()
        xLog("historyList \(historyList)")
        historyCollectionView.isHidden = historyList.count == 0
        historyCollectionView.reloadData()
        historyCollectionView.layoutIfNeeded()
        
        historyLayoutHeight.constant = CGFloat(50 + (historyList.count == 0 ? 0: historyCollectionView.contentSize.height))
    }
    
    func updateHistoryList(id: String, name: String) {
        
        let result = id + "|" + name
        var list = fetchSearchHistoryList()
        
        let history = list.filter { $0 == result }
        if history.count > 0 {
            // 已经存在了
            list.remove(result)
        }
        
        if list.count > 0 {
            list.insert(result, at: 0)
            
        } else {
            list.append(result)
        }
        saveSearchHistory(array: list)
    }
    
    
    func saveSearchHistory(array: [String]) {
        xLog("保存 数据： \(array)")
        // 最多保存 5 条数据，截取前 5 条
        UserDefaults.standard.set(Array(array.prefix(5)), forKey: "CitySearchHistory-\(UserProfile.userId)")
    }
    
    func fetchSearchHistoryList() -> [String] {
        if let list = UserDefaults.standard.array(forKey: "CitySearchHistory-\(UserProfile.userId)") as? [String] {
            xLog("fetchSearchHistoryList \(list)")
            return list
        }
        return []
    }
    
    
    
}

extension CountryPickerView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(for: indexPath, cellType: ReusableTableViewCell.self)
        let model = list[indexPath.row]
        cell.textLabel?.text = model.label
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = list[indexPath.row]
        xLog(model.label)
        if model.id == -1 {
            // 不限
            updateHistoryList(id: String(model.id), name: model.label)
            didSelectedBlock?(model.id, model.label)
            return
        }
        if model.level == 0 {
            // 选中国家
            currentView.isHidden = false
            currentViewLayoutHeight.constant = 80
            currentCountryView.isHidden = false
            currentCountryLabel.text = model.label
            selectedCountryModel = model
            
        } else if model.level == 1 {
            // 选择省份
            provinceView.isHidden = false
            currentProvinceLabel.text = model.label
            selectedProvinceModel = model
            
        } else {
            // 选择城市
            selectedCityModel = model
            
        }
        
        list = model.children
        if model.children.count == 0 {
            var name = selectedCountryModel!.label
            if let provinceModel = selectedProvinceModel {
                name = name + "-" + provinceModel.label
            }
            
            if let cityModel = selectedCityModel {
                name = name + "-" + cityModel.label
            }
            updateHistoryList(id: String(model.id), name: name)
            didSelectedBlock?(model.id, name)
        }
    }
    
}

extension CountryPickerView: UICollectionViewDelegate, UICollectionViewDataSource, YLCollectionFlowLayoutDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        historyList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: CountryPickerHistoryCell.self)
        let string = historyList[indexPath.row]
        cell.nameLabel.text = String(string.split(separator: "|").last!)
        return cell
    }
    
    func collectionView(sizeForItemAt index: Int) -> CGSize {
        let string = historyList[index]
        let name = String(string.split(separator: "|").last!)
        
        var width = name.sg.size(width: CGFLOAT_MAX, font: .systemFont(ofSize: 12)).width
        
        width += CGFloat(8*2)
        width = ceil(width)
        width = min(xScreenW - 24*2, width)
        return CGSizeMake(width, 24)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
    }
}

